<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入聚合规则名称"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建" type="primary" icon="el-icon-plus" size="medium" perms="PT_USER_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="ruleMainCode" label="聚合规则编码" align="center"/>
        <el-table-column prop="ruleMainName" label="聚合规则名称" align="center"/>
        <el-table-column label="规则类型" align="center">
          <template slot-scope="scope">
            {{ruleType.find(item => item.value == scope.row.ruleType).label}}
          </template>
        </el-table-column>
        <el-table-column label="数据返回类型" align="center">
          <template slot-scope="scope">
            {{returnDataType.find(item => item.value == scope.row.resType).label}}
          </template>
        </el-table-column>
        <el-table-column prop="ruleDes" label="聚合规则描述" show-overflow-tooltip align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"/>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"/>
        <el-table-column label="更新时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <perButton label="配置规则" type="primary" size="mini" perms="PT_USER_ADD"
                       @click="configRuleOpenDialog(row)"></perButton>
            <perButton label="编辑" type="warning" size="mini" perms="PT_USER_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" perms="PT_USER_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 新建 -->
    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newAccountFormRef"
            :rules="newAccountModelRules"
            :model="newAccountModel"
            :disabled="detailsDisabled"
            label-width="110px"
          >
            <el-form-item label="聚合规则名称" prop="ruleMainName">
              <el-input v-model="newAccountModel.ruleMainName"/>
            </el-form-item>
            <el-form-item label="规则类型" prop="ruleType">
              <el-select v-model="newAccountModel.ruleType" placeholder="请选择">
                <el-option
                  v-for="item in ruleType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据返回类型" prop="resType">
              <el-select v-model="newAccountModel.resType" placeholder="请选择">
                <el-option
                  v-for="item in returnDataType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="聚合规则描述">
              <el-input v-model="newAccountModel.ruleDes" :rows="2" type="textarea"/>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 配置规则1 -->
    <yc-dialog ref="configDialog1" :dialogTitle="dialogTitle" :show-center="false" dialog-width="35%">
      <template #content>
        <div class="dialog-content">
          <div class="d-flex align-items-center mb-3">
            <div class="mr-2 font-weight-bold font-15">单数据元：</div>
            <el-button type="primary" plain class="button-new-tag" size="small">数据元</el-button>
          </div>
          <div class="d-flex">
            <div class="mr-2 font-weight-bold font-15">公式规则：</div>
            <div>
              <div v-for="(item,index) in gsgzList" :key="index" class="font-14 mb-3">
                <div class="mb-3 font-weight-bold">{{item.label}}</div>
                <div class="d-flex">
                  <div v-for="(itemY,indexY) in item.children" :key="itemY.value" class="mb-1 ml-2 mr-2">
                    <el-button class="pointer" @click="gsgzClick(itemY.value)"
                               :type="checkGsgz==itemY.value?'primary':''" plain>{{itemY.label}}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="configSave1">确定</el-button>
        <el-button @click="$refs.configDialog1.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 配置规则2 -->
    <yc-dialog ref="configDialog2" :dialogTitle="dialogTitle" :show-center="false" dialog-width="40%">
      <template #content>
        <div class="dialog-content">
          <div class="d-flex align-items-center mb-3">
            <div class="font-weight-bold font-15" style="width: 120px">单数据元：</div>
            <el-button type="primary" plain class="button-new-tag" size="small">数据元集合</el-button>
          </div>
          <div class="d-flex align-items-center mb-3">
            <div class="font-weight-bold font-15" style="width: 120px">数据元逻辑规则：</div>
            <div class="flex-2">
              <el-select v-model="sjyljghCkeckData" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in sjyljghList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="configSave2">确定</el-button>
        <el-button @click="$refs.configDialog2.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 配置规则3 -->
    <yc-dialog ref="configDialog3" :dialogTitle="dialogTitle" :show-center="false">
      <template #content>
        <div class="dialog-content">
          <div class="d-flex align-items-center flex-wrap px-3">
            <div class="mr-3 font-weight-bold font-15">聚合规则逻辑</div>
            <el-tag type="info" effect="plain" closable class="mr-3 mb-2" :class="{active:index == num}"
                    @click="changes(index)" @close="delTag(index)"
                    v-for="(item, index) in tagList" :key="index">{{ item }}
            </el-tag>
          </div>
          <div class="d-flex p-3" style="height: 300px;">
            <div class="shadow rounded-lg mr-4 p-3" style="width: 150px;">
              <div class="d-flex justify-content-between py-2 pointer" v-for="(item, index) in tagSelectList"
                   :key="index"
                   @click="tagSelectIndexChange(index)">
                <div :class="tagSelectIndex == index ? 'text-primary' : ''">{{ item }}</div>
                <i class="el-icon-arrow-right" :class="tagSelectIndex == index ? 'text-primary' : ''"></i>
              </div>
            </div>

            <div class="shadow rounded-lg col over-auto p-3">
              <div class=" over-auto" v-if="tagSelectIndex == 0">
                <el-button size="mini" @click="pushString('0', '数据元')"
                           class="ml-0 mr-3 mb-3 pl-3 pr-3">数据元
                </el-button>
              </div>
              <div class=" over-auto" v-if="tagSelectIndex == 1">
                <el-button size="mini" v-for="(item, index) in symbolList" :key="index"
                           @click="pushString('1', item)"
                           class="ml-0 mr-3 mb-3 pl-5 pr-5">{{ item }}
                </el-button>
              </div>
              <div class=" " v-if="tagSelectIndex == 2">
                <el-input size="mini" type="textarea" placeholder="请输入" v-model="tagInput"
                          @blur="pushString('2', tagInput)"></el-input>
              </div>
              <div class=" over-auto" v-if="tagSelectIndex == 3">
                <el-button size="mini" v-for="(item, index) in booleanList" :key="index"
                           @click="pushString('3', item.name, item.code)"
                           class="ml-0 mr-3 mb-3 pl-3 pr-3">{{ item.name }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="configSave3">确定</el-button>
        <el-button @click="$refs.configDialog3.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryPage,
    insertByModel,
    updateByModel,
    deleteByModel,
    queryDetailList,
    queryBaseList,
    saveDetail
  } from "@/api/basicsMessage/polymerizationRule"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",
        tableData: [],
        tableItemObj: {},
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,

        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },

        newAccountModel: {
          ruleMainName: "",
          ruleType: "",
          resType: "",
          id: 0
        },
        newAccountModelRules: {
          ruleMainName: [{required: true, message: "请输入聚合规则名称", trigger: "blur"}],
          ruleType: [{required: true, message: "请选择规则类型", trigger: "change"}],
          resType: [{required: true, message: "请选择数据返回类型", trigger: "change"}],
        },

        ruleType: [
          {value: '0', label: '公式规则(日期)'},
          {value: '1', label: '公式规则(实时)'},
          {value: '2', label: '运算规则'},
        ],
        returnDataType: [
          {value: 'number', label: '数值型'},
          {value: 'bo', label: '布尔型'},
        ],

        // 公式规则
        gsgzList: [
          {
            value: '0', label: 'Sum逻辑', children: [
              {value: 'SUM-TODAY', label: '设备当日总和'},
              {value: 'SUM-MONTH', label: '设备当月总和'},
              {value: 'SUM-YEAR', label: '设备当年总和'},
            ]
          },
          {
            value: '1', label: 'Avg逻辑', children: [
              {value: 'AVG-TODAY', label: '设备当日平均'},
              {value: 'AVG-MONTH', label: '设备当月平均'},
              {value: 'AVG-YEAR', label: '设备当年平均'},
            ]
          },
          {
            value: '2', label: 'Top逻辑', children: [
              {value: 'TOP-TODAY', label: '设备当日最高'},
              {value: 'TOP-MONTH', label: '设备当月最高'},
              {value: 'TOP-YEAR', label: '设备当年最高'},
            ]
          },
          {
            value: '3', label: 'Low逻辑', children: [
              {value: 'LOW-TODAY', label: '设备当日最低'},
              {value: 'LOW-MONTH', label: '设备当月最低'},
              {value: 'LOW-YEAR', label: '设备当年最低'},
            ]
          },
          {
            value: '3', label: 'Cou逻辑', children: [
              {value: 'COUNT-TODAY', label: '设备当日累计'},
              {value: 'COUNT-MONTH', label: '设备当月累计'},
              {value: 'COUNT-YEAR', label: '设备当年累计'},
            ]
          },
        ],
        checkGsgz: "",

        sjyljghList: [
          {value: 'SUM', label: '求和'},
          {value: 'AVG', label: '求平均值'},
          {value: 'TOP', label: '求最大值'},
          {value: 'LOW', label: '求最小值'},
          {value: 'COUNT', label: '累计'},
        ],
        sjyljghCkeckData: '',


        configModel: {
          zeroFalseValue: "",
          oneTrueValue: "",
        },
        configModelRules: {
          zeroFalseValue: [{required: true, message: "请输入结果值TRUE(1)", trigger: "blur"}],
          oneTrueValue: [{required: true, message: "请输入结果值FALSE(0)", trigger: "blur"}],
        },
        tagList: [],
        num: null,
        tagSelectList: ["数据元", "运算符", "输入框", "布尔字典"],
        tagSelectIndex: 0,
        symbolList: ["(", ")", "+", "-", "*", "/", ">", "<", "==", "&&", "||"],
        tagInput: "",
        booleanList: [],
        mapString: [],

        dialogTitle: "",
        centerTitle: "",
        detailsDisabled: false,
        addOrUpdateLoading: false
      }
    },
    created() {
      this.getAccountData()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {userName, status} = tableInfo
          const {object} = await queryPage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {object} = await queryPage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },


      /**
       * 删除按钮
       */
      async handlerDelete({id}) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {message, status} = await deleteByModel({id})
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      /**
       * 新建
       * */
      async handlerAccount() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"

        this.detailsDisabled = false
        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true

        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
      },

      /**
       * 修改
       */
      handlerEdit(row) {
        this.dialogTitle = "编辑"
        this.centerTitle = "编辑"

        this.newAccountModel.id = row.id
        this.newAccountModel.ruleMainName = row.ruleMainName
        this.newAccountModel.ruleType = row.ruleType
        this.newAccountModel.resType = row.resType
        this.newAccountModel.ruleDes = row.ruleDes

        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
      },
      dialogSave() {
        this.$refs.newAccountFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.newAccountModel.id) {
              const {message, status} = await updateByModel({...this.newAccountModel})
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const {message, status} = await insertByModel({...this.newAccountModel})
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      configRuleOpenDialog(row) {
        this.dialogTitle = "配置规则"
        this.tagList = []
        this.mapString = []
        this.tableItemObj = JSON.parse(JSON.stringify(row))

        this.detailsDisabled = false
        this.addOrUpdateLoading = false

        if (row.ruleType == '0') {
          this.checkGsgz = row.yunType
          this.$refs.configDialog1.dialogVisible = true
        } else if (row.ruleType == '1') {
          this.sjyljghCkeckData = row.yunType
          this.$refs.configDialog2.dialogVisible = true
        } else {
          this.tagInput = ""
          this.queryDetailList()
          this.queryBaseList()
          this.configModel.zeroFalseValue = row.zeroFalseValue
          this.configModel.oneTrueValue = row.oneTrueValue
          this.$refs.configDialog3.dialogVisible = true
        }
      },

      queryDetailList() {
        queryDetailList({
          ruleMainCode: this.tableItemObj.ruleMainCode
        }).then(res => {
          let tempArr = res.object || []
          this.mapString = tempArr.map(item => {
            return {
              itemType: item.itemType,
              itemValue: item.itemValue,
              itemValueName: item.itemValueName,
            }
          })
          tempArr.forEach(element => {
            this.tagList.push(element.itemValueName)
          })
        })
      },
      queryBaseList() {
        queryBaseList().then(res => {
          this.booleanList = res.object
        })
      },

      gsgzClick(data) {
        this.checkGsgz = data
      },

      pushString(type, val, code) {
        if (this.num != null) {
          this.tagList.splice(this.num, 1, val)
          this.mapString.splice(this.num, 1, {
            itemType: type,
            itemValue: code ? code : val,
            itemValueName: val
          })
          this.num = null
        } else {
          this.tagList.push(val)
          this.mapString.push({
            itemType: type,
            itemValue: code ? code : val,
            itemValueName: val
          })
        }
      },
      delTag(index) {
        this.tagList.splice(index, 1)
        this.mapString.splice(index, 1)
      },
      changes(key) {
        this.num = key
      },
      tagSelectIndexChange(index) {
        this.tagSelectIndex = index
      },

      configSave1() {
        if (this.checkGsgz) {
          this.addOrUpdateLoading = true
          updateByModel({
            id: this.tableItemObj.id,
            yunType: this.checkGsgz
          }).then(res => {
            if (res.status == 200) {
              this.getAccountData()
              this.$refs.configDialog1.dialogVisible = false
              this.$message.success(res.message)
            }
            this.addOrUpdateLoading = false
          })
        } else {
          this.$message({
            message: '请选择一个公式规则',
            type: 'warning'
          });
        }
      },
      configSave2() {
        if (this.sjyljghCkeckData) {
          this.addOrUpdateLoading = true
          updateByModel({
            id: this.tableItemObj.id,
            yunType: this.sjyljghCkeckData
          }).then(res => {
            if (res.status == 200) {
              this.getAccountData()
              this.$refs.configDialog2.dialogVisible = false
              this.$message.success(res.message)
            }
            this.addOrUpdateLoading = false
          })
        } else {
          this.$message({
            message: '请选择数据元逻辑规则',
            type: 'warning'
          });
        }
      },
      configSave3() {
        if (this.tagList.length > 0) {
          saveDetail({
            ruleMainCode: this.tableItemObj.ruleMainCode,
            zeroFalseValue: this.configModel.zeroFalseValue,
            oneTrueValue: this.configModel.oneTrueValue,
            mapString1: JSON.stringify(this.mapString)
          }).then(res => {
            if (res.status == 200) {
              this.getAccountData()
              this.$refs.configDialog3.dialogVisible = false
              this.$message.success(res.message)
            }
            this.addOrUpdateLoading = false
          })
        } else {
          this.$message({
            message: '请选择聚合规则逻辑',
            type: 'warning'
          });
        }
      },
      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }

  .active {
    background-color: #00557F;
    color: #fff;
  }
</style>
<style>
  .el-button--primary.is-plain:focus, .el-button--primary.is-plain:hover {
    color: #409EFF;
    background: #ecf5ff;
    border-color: #b3d8ff;
  }
</style>
